// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.android.cloudapp;

import android.net.LocalSocket;
import android.net.LocalSocketAddress;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;

public class CloudAppUnixSocket {
    private static final String TAG = "CloudAppUnixSocket";
    private LocalSocket mSocket = null;
    private InputStream mInputStream = null;
    private OutputStream mOutputStream = null;
    private String mIpcName;

    public CloudAppUnixSocket(String ipcName) {
        mIpcName = ipcName;
    }

    public int connect() {
        mSocket = new LocalSocket();
        LocalSocketAddress address = new LocalSocketAddress(mIpcName, LocalSocketAddress.Namespace.ABSTRACT);
        try {
            mSocket.connect(address);
            mSocket.setSoTimeout(3000);
            mInputStream = mSocket.getInputStream();
            mOutputStream = mSocket.getOutputStream();
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public void close() {
        try {
            mSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int send(byte[] data) {
        try {
            mOutputStream.write(data, 0, data.length);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        return data.length;
    }

    public int recv(byte[] buf, int len) {
        int bytes = 0;
        int recvLen = 0;
        while (len > 0) {
            try {
                bytes = mInputStream.read(buf, recvLen, len);
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
            if (bytes != -1) {
                len -= bytes;
                recvLen += bytes;
            }
        }
        return recvLen;
    }
}
